"""
Case Type   : borrow_memory
Case Name   : 主节点发起指定分区部分列行列转换请求
Create At   : 2025/4/28
Owner       : @li-xin12345
Description :
    1、设置相关参数有效值
    htap_borrow_mem_percent=0
    max_imcs_cache=100MB
    lmemfabric_client_path依赖rackmanager,当前使用默认值，不做更改
    max_borrow_memory=256MB;
    enable_borrow_memory=on;
    2、建表插入数据
    3、主节点发起指定分区行列转换请求
    4、查看query_imcstore_views视图
    5、查询系统视图GS_TOTAL_MEMORY_DETAIL(需enable_memory_limit为on)
    6、查看临时文件（临时文件存放目录：base/imcu）
    7、备机查询
    8、清理环境
Expect      :
    1、成功
    2、成功
    3、成功
    4、成功
    5、成功
    6、成功
    7、成功
    8、成功
History     :
"""

import os
import unittest

from yat.test import Node
from yat.test import macro

from testcase.utils.CommonSH import CommonSH
from testcase.utils.Common import Common
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class BorrowMemoryTest(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_db_sh = CommonSH('PrimaryDbUser')
        self.std1_db_sh = CommonSH('Standby1DbUser')
        self.pri_node_sh = Node('PrimaryDbUser')
        self.std1_node_sh = Node('Standby1DbUser')
        self.constant = Constant()
        self.common = Common()
        self.tb_name = 't_htap_borrow_memory_0032'
        self.param_names = ['max_imcs_cache', 'enable_borrow_memory',
                            'max_borrow_memory', 'htap_borrow_mem_percent',
                            'enable_memory_limit', 'max_process_memory']
        self.default_values = [self.common.show_param(i) for i in
                               self.param_names]
        self.param_values = ['100MB', 'on', '256MB', 0, 'on', '10GB']
        self.expect_values = [str(i) for i in self.param_values]
        self.file_path = os.path.join(macro.DB_INSTANCE_PATH, 'base', 'imcu')

    def test_borrow_memory(self):
        text = '-----step1:设置相关参数有效值;expect:成功-----'
        self.log.info(text)
        for param, current_val, expect_val in zip(
                self.param_names, self.default_values, self.param_values):
            if current_val != expect_val:
                set_res = self.pri_db_sh.execute_gsguc(
                   'set', self.constant.GSGUC_SUCCESS_MSG,
                    f'{param}={expect_val}')
                self.log.info(set_res)
                self.assertTrue(set_res, '执行失败：' + text)

        res = self.pri_db_sh.restart_db_cluster()
        self.log.info(res)
        self.assertTrue(res, '执行失败：' + text)
        status = self.pri_db_sh.get_db_cluster_status()
        self.assertTrue("Normal" or "Degrade" in status)

        current_values = [self.common.show_param(i) for i in self.param_names]
        self.log.info(current_values)
        self.assertEqual(self.expect_values, current_values, '执行失败：' + text)

        text = '-----step2:建表插入数据;expect:成功-----'
        self.log.info(text)
        sql = f'''drop table if exists {self.tb_name};
        create table {self.tb_name}(
        c1 integer(20),
        c2 varchar(20))
        partition by range (c1)
        (
        partition p1 values less than (20000000),
        partition p2 values less than (30000000),
        partition p3 values less than (40000000),
        partition p4 values less than (maxvalue)
        );
        insert into {self.tb_name} values (generate_series(1, 20000000));
        insert into {self.tb_name} values (generate_series(20000001,20000099));
        '''
        res = self.pri_db_sh.execut_db_sql(sql)
        self.log.info(res)
        self.assertIn(self.constant.DROP_TABLE_SUCCESS, res, '执行失败：' + text)
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS, res,
                      '执行失败：' + text)
        self.assertIn('INSERT 0 20000000', res, '执行失败：' + text)
        self.assertIn('INSERT 0 99', res, '执行失败：' + text)

        text = '-----step3:主节点发起指定分区部分列行列转换请求;expect:成功-----'
        self.log.info(text)
        sql = f'alter table {self.tb_name} modify partition p1 imcstored(c2);'
        res = self.pri_db_sh.execut_db_sql(sql)
        self.log.info(res)
        self.assertIn(self.constant.ALTER_TABLE_MSG, res, '执行失败：' + text)

        text = '-----step4:查看query_imcstore_views视图;expect:成功-----'
        self.log.info(text)
        sql = f"select * from query_imcstore_views();"
        res = self.std1_db_sh.execut_db_sql(sql)
        self.log.info(res)
        self.assertIn('COMPLETE', res, '执行失败：' + text)

        text = '-----step5:查看系统视图GS_TOTAL_MEMORY_DETAIL;expect:成功-----'
        self.log.info(text)
        sql = (f"select * from GS_TOTAL_MEMORY_DETAIL "
               f"where memorytype like 'imcs%';")
        res = self.std1_db_sh.execut_db_sql(sql)
        self.log.info(res)
        res_lines = res.split('\n')[2:-1]
        self.log.info(res_lines)
        res = [int(line.split('|')[2].strip()) for line in res_lines[:2]]
        self.log.info(res)
        self.assertEqual(res[0], 100, '执行失败：' + text)
        self.assertGreaterEqual(res[1], 96, '执行失败：' + text)

        text = '-----step6:查看临时文件;expect:成功-----'
        self.log.info(text)
        sql = (f"select relfilenode from pg_class "
               f"where relname = '{self.tb_name}';")
        relfilenode = self.pri_db_sh.execut_db_sql(sql).splitlines()[-2].strip()
        self.log.info(relfilenode)
        cmd = f'ls {self.file_path} |grep {relfilenode}'
        res = self.common.get_sh_result(self.std1_node_sh, cmd)
        self.log.info(res)
        self.assertGreater(len(res.split('\n')), 0, '执行失败：' + text)

        text = '-----step7:备机查询;expect:成功-----'
        self.log.info(text)
        sql = (f"set enable_imcsscan to on;"
               f"explain analyze select c2 from {self.tb_name} partition(p1);")
        res = self.std1_db_sh.execut_db_sql(sql)
        self.log.info(res)
        self.assertIn('IMCStore Scan', res, '执行失败：' + text)

    def tearDown(self):
        text = '-----step8:清理环境; expect:成功-----'
        self.log.info(text)
        sql = f'drop table if exists {self.tb_name} cascade;'
        drop_res = self.pri_db_sh.execut_db_sql(sql)
        self.log.info(drop_res)

        current_values = [self.common.show_param(i) for i in self.param_names]
        self.log.info(current_values)
        reset_flag = False
        if current_values != self.default_values:
            for param_name, current_val, default_val in zip(
                    self.param_names, current_values, self.default_values):
                if current_val != default_val:
                    set_res = self.pri_db_sh.execute_gsguc(
                        'set', self.constant.GSGUC_SUCCESS_MSG,
                        f'{param_name}={default_val}')
                    self.log.info(set_res)
                    self.assertTrue(set_res, '执行失败：' + text)
                    reset_flag = True
        if reset_flag:
            res = self.pri_db_sh.restart_db_cluster()
            self.log.info(res)
            status = self.pri_db_sh.get_db_cluster_status()
            self.assertTrue("Normal" or "Degrade" in status)
            res = [self.common.show_param(i) for i in self.param_names]
            self.log.info(res)
            self.assertEqual(self.default_values, res, '执行失败：' + text)
        self.assertIn(self.constant.DROP_TABLE_SUCCESS, drop_res,
                      '执行失败：' + text)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')